<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12" >
            <a-form-model-item label="付款金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="paymentMoney">
              <a-input-number v-model="model.paymentMoney" placeholder="请输入付款金额" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="开票日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="paymentDate">
              <j-date placeholder="请选择开票日期" v-model="model.paymentDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="收票管理子表" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="paymentManagementDetailTable.loading"
          :columns="paymentManagementDetailTable.columns"
          :dataSource="paymentManagementDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
        />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

import { getAction, postAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import {
  getRefPromise,
  VALIDATE_FAILED,
  validateFormModelAndTables
} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'

export default {
  name: 'PaymentManagementFrom',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model:{
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        paymentMoney:[{required: true,message:'请输入付款金额'}],
      },
      refKeys: ['paymentManagementDetail', ],
      tableKeys:['paymentManagementDetail', ],
      activeKey: 'paymentManagementDetail',
      // 收票管理子表
      paymentManagementDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '采购订单code',
            key: 'orderCode',
            type: JVXETypes.input,
            disabled:true,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '收货金额',
            key: 'receiptNum',
            type: JVXETypes.inputNumber,
            disabled:true,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '已付款金额',
            key: 'paymentNum',
            type: JVXETypes.inputNumber,
            disabled:true,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '未付款金额',
            key: 'unpaidNum',
            type: JVXETypes.inputNumber,
            disabled:true,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '订单分配付款金额',
            key: 'allocationNum',
            type: JVXETypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [
              { required: true, message: '请输入订单分配付款金额' },
            ]
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
        ]
      },
      url: {
        add: "/procurement/paymentManagement/add",
        edit: "/procurement/paymentManagement/edit",
        queryById: "/procurement/paymentManagement/queryById",
        paymentManagementDetail: {
          list: '/procurement/paymentManagement/querypaymentManagementDetailByMainId',
          selectByMainId: '/procurement/paymentManagement/selectByMainId',
        },
      }
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled(){
      return this.disabled
    },
  },
  created () {
  },
  methods: {
    handleOk() {
/*      let price=0
      for (let i = 0; i < this.paymentManagementDetailTable.dataSource.length; i++) {
        price=price+this.paymentManagementDetailTable.dataSource[i].allocationNum
        if(this.paymentManagementDetailTable.dataSource[i].allocationNum>this.paymentManagementDetailTable.dataSource[i].unpaidNum){
          this.$message.error("订单分配收票金额不能大于未付款金额")
          return
        }
      }
      if(price!==this.model.paymentMoney){
        return this.$message.error("订单分配收票金额需要等于付款金额")
      }*/
      /** 触发表单验证 */
      this.getAllTable().then(tables => {
        /** 一次性验证主表和所有的次表 */
        return validateFormModelAndTables(this.$refs.form,this.model, tables)
      }).then(allValues => {
        /** 一次性验证一对一的所有子表 */
        return this.validateSubForm(allValues)
      }).then(allValues => {
        if (typeof this.classifyIntoFormData !== 'function') {
          throw this.throwNotFunction('classifyIntoFormData')
        }
        let formData = this.classifyIntoFormData(allValues)
        // 发起请求
        return this.request(formData)
      }).catch(e => {
        if (e.error === VALIDATE_FAILED) {
          // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
          this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
        } else {
          console.error(e)
        }
      })
    },
    add(records) {
      if (typeof this.addBefore === 'function') this.addBefore(records)
      // 默认新增空数据
      let rowNum = this.addDefaultRowNum
      if (typeof rowNum !== 'number') {
        rowNum = 1
        console.warn('由于你没有在 data 中定义 addDefaultRowNum 或 addDefaultRowNum 不是数字，所以默认添加一条空数据，如果不想默认添加空数据，请将定义 addDefaultRowNum 为 0')
      }
      this.eachAllTable((item) => {
        //update-begin-author:taoyan date:20210315 for: 一对多jvex 默认几行不好使了 LOWCOD-1349
        setTimeout(()=>{
          item.addRows()
        }, 30)
        //update-end-author:taoyan date:20210315 for: 一对多jvex 默认几行不好使了 LOWCOD-1349
      })
      if (typeof this.addAfter === 'function') this.addAfter(this.model)
      this.edit(this.model)
    },
    addBefore(records){
      records.forEach(record => {
        record.main = record.orderId
      })
      postAction(this.url.paymentManagementDetail.selectByMainId,records).then((res) => {
        if(res.success){
          console.log("111111111111111111",res.result)
          this.paymentManagementDetailTable.dataSource.push(...res.result)
        }
      })

    },
    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.paymentManagementDetail.list, params, this.paymentManagementDetailTable)
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues){
      return new Promise((resolve,reject)=>{
        Promise.all([
        ]).then(() => {
          resolve(allValues)
        }).catch(e => {
          if (e.error === VALIDATE_FAILED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        paymentManagementDetailList: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg){
      this.$message.error(msg)
    },

  }
}
</script>

<style scoped>
</style>